package com.stream.service.impl;

import com.google.common.collect.Maps;
import com.stream.model.entity.TokenEntity;
import com.stream.repository.TokenRepository;
import com.stream.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by yebaokang on 2017/5/22.
 */

@Service("tokenService")
public class TokenServiceImpl implements TokenService{

    @SuppressWarnings({"all"})
    @Autowired
    private TokenRepository tokenRepository;

    public static final int EXPIRE = 43200; //值为3600*12

    @Override
    public TokenEntity queryByUserId(Long userId) {
        return  tokenRepository.queryByUserId(userId);
    }

    @Override
    public TokenEntity queryByToken(String token) {
        return tokenRepository.queryByToken(token);
    }

    @Override
    public void save(TokenEntity token) {
        tokenRepository.save(token);
    }

    @Override
    public void update(TokenEntity token) {
        tokenRepository.update(token);
    }

    @Override
    public Map<String, Object> createToken(Long userId) {
        //生成token
        String token = UUID.randomUUID().toString();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expire = new Date(now.getTime() + EXPIRE * 1000);

        TokenEntity tokenEntity = tokenRepository.queryByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expire);
            tokenEntity.setUpdateTime(now);

            tokenRepository.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expire);
            tokenEntity.setUpdateTime(now);

            tokenRepository.update(tokenEntity);
        }

        HashMap<String, Object> map = Maps.newHashMap();
        map.put("token", token);
        map.put("expire", EXPIRE);

        return map;
    }
}
